import React, { ErrorInfo, ReactNode } from 'react';

interface ErrorBoundaryProps {
  children: ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error?: Error;
  componentStack: string
}

export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = {
      hasError: false,
      error: undefined,
      componentStack: ''
    };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
    this.setState({
      hasError: true,
      error: error,
      componentStack: errorInfo.componentStack
    })
    // 在这里可以记录错误信息，例如发送给服务器或者显示错误提示
    console.error('Caught an error:', error, errorInfo.componentStack);
  }

  render(): ReactNode {
    if (this.state.hasError) {
      // 自定义错误界面，可以根据实际需求进行定制
      return (
        <div>
          <h1>发生了错误</h1>
          <div>{this.state.error?.message}</div>
          <div>{this.state.componentStack}</div>
        </div>
      );
    }
    return this.props.children;
  }
}

export default ErrorBoundary;

